<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目" prop="topic">
        <el-input
          v-model="queryParams.topic"
          placeholder="请输入题目"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="抽奖模式" prop="lotteryMode">
        <el-select v-model="queryParams.lotteryMode" placeholder="请选择抽奖模式" clearable size="small">
          <el-option
            v-for="dict in lotteryModeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      
      <el-col :span="1.5">
        <a :href="BASE_URL+'/papertopic/papertopic/downloadExcel'" download="模板.xlsx">
          <el-button
              type="primary"
              plain
              icon="el-icon-download"
              size="mini"
            >下载模板</el-button>
        </a>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          class="upload-demo"
          :action="BASE_URL+'/papertopic/papertopic/importExcel'"
          :on-success="uploadSuccess"
          :show-file-list="false"
          :multiple='false'
          :on-error="uploadError"
          :before-upload="startUpload"
          :file-list="fileList">
          <el-button
            plain
            type="primary"
            icon="el-icon-upload"
            size="mini"
          >导入</el-button>
        </el-upload>
        
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lotterytopic:lotterytopic:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lotterytopic:lotterytopic:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lotterytopic:lotterytopic:remove']"
        >删除</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lotterytopicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" :index="(queryParams.pageNum-1)*10+1" />
      <el-table-column label="题目" align="center" prop="topic" />
      <!-- <el-table-column label="选项" align="center" prop="topic" />
      <el-table-column label="答案" align="center" prop="topic" /> -->
      <!-- <el-table-column label="分数" align="center" prop="topicIntegral" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <!-- <el-table-column label="抽奖模式" align="center" prop="lotteryMode" :formatter="lotteryModeFormat" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lotterytopic:lotterytopic:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lotterytopic:lotterytopic:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改抽奖 题对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="top">
        <el-form-item label="题目" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入题目" />
        </el-form-item>
        <!-- <el-form-item label="分数" prop="topicIntegral">
          <el-input v-model="form.topicIntegral" placeholder="请输入分数"  @input="form.topicIntegral = form.topicIntegral.replace(/[^\.\d]/g,'')"/>
        </el-form-item> -->
        <!-- <el-form-item label="题目类型" prop="lotteryMode">
          <el-select v-model="form.lotteryMode" placeholder="请选择抽题目类型">
            <el-option
              v-for="dict in lotteryModeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="选项(如果是正确答案请在后方勾选)" prop="lotteryMode">
          <div class="chooseOptionsBox" v-for="(item,index) in form.ttLotteryAnswerList" :key="index">
            <div class="chooseOptions">
              {{index == 0?'A. ':''}}
              {{index == 1?'B. ':''}}
              {{index == 2?'C. ':''}}
              {{index == 3?'D. ':''}}
            </div>
            <el-input class="optionsInp" v-model="form.ttLotteryAnswerList[index].answer" placeholder="请输入选项"></el-input>
            <el-checkbox class="isTrue" v-model="item.isRightKey"></el-checkbox>
            <el-button class="del" @click="form.ttLotteryAnswerList.splice(index,1)" size="small" type="danger">删除</el-button>
          </div>
          <el-button class="addOptions" v-if="form.ttLotteryAnswerList&&form.ttLotteryAnswerList.length<4" @click="addOptions">添加选项</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadFile,listLotterytopic, getLotterytopic, delLotterytopic, addLotterytopic, updateLotterytopic, exportLotterytopic } from "@/api/lotterytopic/lotterytopic";
import {BASE_URL} from '@/utils/configRequestUploadUrl'
export default {
  name: "Lotterytopic",
  components: {
  },
  data() {
    return {
      BASE_URL,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 抽奖 题表格数据
      lotterytopicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 抽奖模式字典
      lotteryModeOptions: ['单选','多选','判断'],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        topic: null,
        lotteryMode: null
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        topic:[
          {required:true,message:'请填写题目',trigger: 'blur'}
        ],
        // topicIntegral:[
        //   {required:true,message:'请填写分数',trigger: 'blur'}
        // ]
      }
    };
  },
  created() {
    this.getList();
    // this.getDicts("sys_lottery_mode").then(response => {
    //   this.lotteryModeOptions = response.data;
    // });
  },
  methods: {
    downFile(){
      downloadFile()
    },
    uploadSuccess(response, file, fileList){
      this.loading = false;
      console.log(response)
      if(response.code == 500){
        this.$message.error(response.msg)
      } else {

        this.$message.success('上传成功')
        this.getList();
      }
    },
    uploadError(){
      this.loading = false;
      this.$message.error('上传失败')
    },
    startUpload(){
      this.loading = true;
    },
    addOptions(){
      this.form.ttLotteryAnswerList.push({
        answer:'',
        isRightKey:0
      })
    },
    /** 查询抽奖 题列表 */
    getList() {
      this.loading = true;
      listLotterytopic(this.queryParams).then(response => {
        this.lotterytopicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 抽奖模式字典翻译
    lotteryModeFormat(row, column) {
      return this.selectDictLabel(this.lotteryModeOptions, row.lotteryMode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        topic: null,
        topicIntegral:10,
        prizeId: null,
        lotteryMode: null,
        ttLotteryAnswerList:[{
          answer:'',
          isRightKey:0
        }],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加抽奖 题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLotterytopic(id).then(response => {
        this.form = response.data;
        this.form.ttLotteryAnswerList = response.data.ttLotteryAnswerList.map((item,index)=>{
          item.isRightKey = item.isRightKey == 1||item.isRightKey?true:false
          return item
        })
        this.open = true;
        this.title = "修改抽奖 题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let flag = true
          if(this.form.ttLotteryAnswerList.length == 0){
            this.$message.warning('请添加选项')
            return
          }
          this.form.ttLotteryAnswerList = this.form.ttLotteryAnswerList.map((item,index)=>{
              let optionsName = ''
              index == 0&&(optionsName = 'A')
              index == 1&&(optionsName = 'B')
              index == 2&&(optionsName = 'C')
              index == 3&&(optionsName = 'D')
              item.answerX = optionsName
              if(this.form.id){
                item.answerId = this.form.id
              }
              
              item.isRightKey = item.isRightKey == 1||item.isRightKey?1:0
              if(item.isRightKey){
                flag = false
              }
              return item
            })
            if(flag){
              this.$message.warning('请勾选正确选项')
              return
            }
          console.log(this.form)
          if (this.form.id != null) {
            
            updateLotterytopic(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLotterytopic(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除抽奖 题编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLotterytopic(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导入按钮操作 */
    handleExport() {
      
    }
  }
};
</script>
<style scoped>
.chooseOptionsBox{
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.chooseOptions{
  margin-right: 20px;
}
.optionsInp{
  width: 80%;
}
.jian{
  margin-left: 20px;
}
.del{
  margin-left: 20px;
}
.isTrue{
  margin-left: 20px;
}
</style>
